import React, { useEffect, useState, useRef } from 'react';
import { Button, View, Form } from '@tarojs/components'
import Module from './components/module';
import VForm from 'taro-vform';
import dayjs from 'dayjs';
import { getCurrentInstance } from '@tarojs/taro'
import { toast, loginData } from '@/utils/utils';
import { fetchInformationCollectionDetail, fakeSaveUserInformation } from '@/server/shop'
import './index.scss';

const collect = (props) => {
  const { detail = {}, onClose } = props
  const { params } = getCurrentInstance().router
  const { goodsId } = params
  const [data, setData] = useState({})
  const { id } = detail
  const account = loginData() || {}
  const form = VForm.useForm();
  const { username, unionId, openId, organizationId, profile } = account
  const { title = '信息采集', description } = data
  useEffect(() => {
    fetchInformationCollectionDetails()
  }, [])
  useEffect(() => {
    const { content } = data
    if (content) {
      setList(JSON.parse(content))
    }

  }, [data])
  const fetchInformationCollectionDetails = () => {
    fetchInformationCollectionDetail({ id, organizationId }).then(val => {
      const { informationCollection } = val
      setData(informationCollection)
    })
  }
  const fakeSaveUserInformations = (data = {}) => {
    fakeSaveUserInformation({ informationCollectionId: id, organizationId, unionId, goodsId, answer: JSON.stringify(data) }).then(e => {
      toast('问卷填写成功')
      onClose();
    })

  }
  function handleSubmit() {
    console.log(form.getFieldsValue())
    form.validateFields().then(async val => {
      const values = form.getFieldsValue();
      Object.keys(values).map(item => {
        if (values[item] instanceof Array) {
          values[item] = values[item].toString();
        }
      })
      fakeSaveUserInformations(values)
    }).catch(errors => { });
  }
  const [list, setList] = useState([]);
  const filterList = (list) => {
    return list.reduce((item, pre) => {
      const { type } = pre;
      if (type === 'cephalogram') {
        return [pre, ...item];
      } else {
        return [...item, pre];
      }
    }, []);
  };
  return (
    <View onClick={(e) => {
      e.stopPropagation()
    }} className="collect_box">
      <View className='collect_title'>{title}{description ? `(${description})` : ''}</View>
      <VForm
        form={form}
      >
        {filterList(list).map((item, index) => {
          const { type } = item;
          const FormItem = Module[type] || null;
          return <FormItem form={form} {...item} key={index}></FormItem>;
        })}

      </VForm>
      <Button onClick={async () => {
        handleSubmit()
      }} block className='collect_btn_box' type="primary" size="large">
        提交
      </Button>
    </View>
  );
};

export default collect